import argparse
import os
import numpy as np
import math

import torchvision.transforms as transforms
from torchvision.utils import save_image

from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable

import torch.nn as nn
import torch.nn.functional as F
import torch

from ai import AiConstant
import ai

parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=100, help="number of epochs of training")
parser.add_argument("--batch_size", type=int, default=128, help="size of the batches")
parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate")
parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient")
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient")
parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
parser.add_argument("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
parser.add_argument("--img_size", type=int, default=28, help="size of each image dimension")
parser.add_argument("--channels", type=int, default=1, help="number of image channels")
parser.add_argument("--sample_interval", type=int, default=400, help="interval betwen image samples")
opt = parser.parse_args()
print(opt)

img_shape = (opt.channels, opt.img_size, opt.img_size)
cuda = True if torch.cuda.is_available() else False


class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()

        def block(input_n, output_n, normalize=True):
            layers = [nn.Linear(input_n, output_n)]
            if normalize:
                layers.append(nn.BatchNorm1d(output_n, 0.8))
            layers.append(nn.ReLU())
            return layers

        self.model = nn.Sequential(
            *block(opt.latent_dim, 128),
            *block(128, 256),
            *block(256, 256),
            *block(256, 512),
            *block(512, 1024),
            nn.Linear(1024, int(np.prod(img_shape))),
            nn.Tanh()
        )

    def forward(self, X):
        out = self.model.forward(X)
        out = out.view(out.shape[0], *img_shape)
        return out


class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()

        self.model = nn.Sequential(
            nn.Linear(int(np.prod(img_shape)), 512),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(512, 256),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Linear(256, 1),
            nn.Sigmoid(),
        )

    def forward(self, img):
        img_flat = img.view(img.size(0), -1)
        validity = self.model(img_flat)

        return validity


def save_gen_imgs(gen_imgs, epoch):
    save_path = ai.AiConstant.OUTPUT_PATH + 'gen/images/'
    ai.utils.utils_file.makedir(save_path)
    save_image(gen_imgs.data[:25], save_path + "%d.png" % epoch, nrow=5, normalize=True)


if __name__ == '__main__':
    """"""
    generator = Generator()
    discriminator = Discriminator()
    if not cuda:
        device = torch.device('cpu')
    else:
        device = torch.device('cuda:0')
    generator.to(device)
    discriminator.to(device)
    optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
    optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
    criterion = nn.BCELoss()
    train_loader, _ = ai.store_data.store_data.DataStore(ai.store_data.store_data_name.MNIST).get_dataloader()

    for epoch in range(opt.n_epochs):
        g_loss_all = 0
        d_loss_all = 0
        batch = 0
        generate_imgs = None
        for i, (imgs, _) in enumerate(train_loader):
            valid = Variable(torch.ones(imgs.size(0), 1).to(device))
            fake = Variable(torch.zeros(imgs.size(0), 1).to(device))
            # Adversarial ground truths
            real_imgs = imgs.to(device)
            random_input = torch.randn(imgs.size(0), opt.latent_dim).to(device)
            # print(random_input.shape)
            generate_imgs = generator(random_input)

            optimizer_G.zero_grad()
            g_loss = criterion(discriminator(generate_imgs), valid)
            g_loss.backward()
            optimizer_G.step()

            optimizer_D.zero_grad()
            d_loss = (criterion(discriminator(generate_imgs.detach()), fake) + criterion(discriminator(real_imgs),
                                                                                         valid)) / 2
            d_loss.backward()
            optimizer_D.step()
            g_loss_all += g_loss.item()
            d_loss_all += d_loss.item()
            batch += 1
        save_gen_imgs(generate_imgs, epoch)
        print("[Epoch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, d_loss_all / batch, g_loss_all / batch))
